<?php
/**
 * User: YL
 * Date: 2019/09/12
 */

namespace restful\traits;

use Illuminate\Redis\Connections\Connection;
use Illuminate\Redis\RedisManager;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Redis;

trait RedisHandler
{
    /**
     * @var Connection
     */
    private static $noPrefixHandler;

    /**
     * 获取redis操作句柄
     * @return Connection
     */
    protected function getRedisHandler()
    {
        return Redis::connection();
    }

    /**
     * 获取无前缀redis操作句柄
     * @return Connection
     */
    protected function getNoPrefixRedisHandler()
    {
        if (is_null(static::$noPrefixHandler)) {
            // 重新实例化redis
            app()->extend('redis', function () {
                $config = config('database.redis', []);
                $config['options']['prefix'] = '';

                $redis = new RedisManager(app('app'), Arr::pull($config, 'client', 'phpredis'), $config);
                static::$noPrefixHandler = $redis->connection();

                return $redis;
            });
        }

        return static::$noPrefixHandler;
    }
}
